/**
 * 全局动画管理器
*/
class AnimationMgr {

	static _inst:AnimationMgr;

	private _aniList:Array<Animation>;
	private _isInit:Boolean;
	private _timer:egret.Timer;
	private _INTERVAL:number = 20;
	private _curTick:number = 0;
	
	public static getInstance():AnimationMgr
	{
		if(!AnimationMgr._inst)
		{
			AnimationMgr._inst = new AnimationMgr();
		}
		return AnimationMgr._inst;
	}

	public constructor() {
	}

	private startTimer():void
	{
		if(!this._timer.hasEventListener(egret.TimerEvent.TIMER))
		{
			this._timer.addEventListener(egret.TimerEvent.TIMER,this.onTimer,this);
		}
		this._timer.reset();
		this._timer.start();
	}
	private stopTimer():void
	{
		this._timer.stop();
		this._timer.removeEventListener(egret.TimerEvent.TIMER,this.onTimer,this);
	}

	private onTimer(evt:egret.TimerEvent):void
	{
		let tick:number = egret.getTimer();
		this._curTick += this._INTERVAL;
		for(let key in this._aniList)
		{
			let ani:Animation = this._aniList[key];			
			if(ani.isPlaying)
			{
				ani.addStartTick(this._INTERVAL,this);
				let m:number = ani.startTick%ani.interval;
				m==0?ani.onTimer(evt):"";
			}
		}
	}

	public init(interval:number=20):void
	{
		this._INTERVAL = 20;
		this._isInit = true;
		this._aniList = new Array<Animation>();	
		this._timer = new egret.Timer(this._INTERVAL);
	}

	/**
	 * 注册动画
	 * @param ani
	*/
	public regist(ani:Animation):void
	{
		if(this._isInit)
		{
			this._aniList.push(ani);
			if(!this._timer.running)
			{
				this.startTimer();
			}			
		}else
		{
			throw new Error("AnimationMgr:请先初始化动画管理器");
		}
	}
	/**
	 * 取消注册的动画
	 * @param ani
	*/
	public unregist(ani:Animation):void
	{
		if(this._isInit)
		{
			let idx = this._aniList.indexOf(ani);
			if(idx)
			{
				this._aniList.splice(idx,1);
			}
			if(this._aniList.length==0 && this._timer.running)
			{
				this.stopTimer();
			}
		}
	}

}